package com.cf.conf;

import com.cf.conf.core.*;
import com.cf.conf.core.model.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * game-server-DisConfig
 * 分布式配置配置
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/6/8 下午 03:46
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(ZConfProperty.class)
public class DisConfConfig {

    @Autowired
    private ZConfProperty zConfProperty;

    @Bean
    public PropertyManager propertyManager() {
        log.info("实例化配置属性管理器！PropertyManager");
        return new PropertyManager();
    }

    @Bean
    public ConfigSetAndUpdateBeanPostprocessor configSetAndUpdateBeanPostprocessor() {
        log.info("实例化属性动态检测器！ConfigSetAndUpdateBeanPostprocessor");
        return new ConfigSetAndUpdateBeanPostprocessor();
    }

    @Bean
    public ConfigService configService() {
        log.info("实例化config持久化器");
        return new ConfigService();
    }


    //##############################redis 动态检测 listener######################################

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter configUpdateListener) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(configUpdateListener, new PatternTopic(zConfProperty.getApp() + "-" + zConfProperty.getProfile()));
        return container;
    }

    @Bean
    UpdateListener robSuccessListener() {
        return new UpdateListener();
    }


    @Bean
    MessageListenerAdapter configUpdateListener(UpdateListener receiver) {
        return new MessageListenerAdapter(receiver, "listen");
    }

    //##############################redis 动态检测 pusher ######################################

    @Bean
    public UpdatePusher updatePusher() {
        log.info("实例化UpdatePusher");
        return new UpdatePusher();
    }
}
